<?php
declare (strict_types=1);

namespace app\controller;

use app\common\library\Log;
use think\Exception;
use think\Request;
use think\facade\Db;



class Order
{
    //购买商品生成订单
    public function getOrder($g_id)
    {
//        取出用户id
        $u_id = cache('u_id');
//       判断用户是否登录
        if (empty($u_id)) {
            return redirect('loginShow');
        }
//        开启事务
        Db::startTrans();
        try {

//        查询订单信息
            $checkData = \app\model\Index::showDetail($g_id)->getData();
//        dd($checkData);
            $data = [
                'u_id' => $u_id,
                'g_id' => $checkData['g_id'],
                'price' => $checkData['price'],
                'num' => $checkData['num'],
                'total' => $checkData['price'] * $checkData['num']
            ];
//        dd($data);
//       订单添加
            $data = \app\model\Order::addOrder($data);
            return view('index/getOrder', compact('data'));
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }

//支付宝支付页面
    public function alipayPage()
    {
        try {
            $g_id = cache('g_id');
            $num = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //        查询商品
            $checkData = \app\model\Index::showDetail($g_id)->getData();
//        查询订单信息
            $result = \app\model\Order::OrderInfo($g_id)->toArray();
            $data = [
                'orderNo' => $num,
                'orderName' => $checkData['name'],
                'orderContent' => $result['total'],
                'orderPrice' => $result['num'],
            ];
            return view('index/alipayPage', compact('data'));
        } catch (Exception $exception) {
            return fail('服务器异常，请重试');
        }

    }

    //回调地址
    public function rollBack()
    {
        $arr = input();
        require_once("./plugins/alipay/config.php");
        require_once('./plugins/alipay/pagepay/service/AlipayTradeService.php');
        $alipaySevice = new \AlipayTradeService($config);
        $result = $alipaySevice->check($arr);
        Log::record('支付成功');
        if ($result) {
            return success('验签成功');
        }
        return success('验签失败');
    }
}
